<template>
    <el-card class="box-card">
        <!-- 搜索栏 -->
        <div class="search-bar">
            <span class="username-label">用户名：</span>
            <el-input v-model="searchQuery" placeholder="请输入用户名" style="width: 200px" clearable
                @clear="handleSearchClear" @keyup.enter="handleSearch">
                <template #append>
                    <el-button :icon="Search" @click="handleSearch" />
                </template>
            </el-input>

            <el-button class="top_btn" type="primary" @click="handleAdd">新增学生</el-button>
        </div>

        <!-- 学生表格 -->
        <el-table :data="filteredStudents" border style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="学号" align="center" width="80" />
            <el-table-column prop="userName" label="用户名" align="center" width="120" />
            <el-table-column prop="realName" label="真实姓名" align="center" width="120" />
            <el-table-column prop="userLevel" label="年级" align="center" width="80">
                <template #default="scope">
                    {{ formatGrade(scope.row.userLevel) }}
                </template>
            </el-table-column>
            <el-table-column prop="sex" label="性别" width="80" align="center">
                <template #default="scope">
                    {{ scope.row.sex === null ? '无' : scope.row.sex == '1' ? '男' : '女' }}
                </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" width="150" align="center" />
            <el-table-column prop="createTime" label="创建时间" min-width="80" align="center" />
            <el-table-column prop="status" label="状态" width="80" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                        {{ scope.row.status === 1 ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center">
                <template #default="scope">
                    <el-button size="small" :type="scope.row.status === 1 ? 'warning' : 'success'" plain
                        @click="handleToggleStatus(scope.row)">
                        {{ scope.row.status === 1 ? '禁用' : '启用' }}
                    </el-button>
                    <el-button size="small" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="info" plain @click="handleLog(scope.row)">日志</el-button>
                    <el-button size="small" type="danger" plain @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]" :small="false" :background="true"
                layout="total, sizes, prev, pager, next, jumper" :total="totalStudents" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </el-card>



</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

// 创建
const router = useRouter()

const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalStudents = ref(0)



const studentList = ref([])


const formatGrade = (level) => {
    const gradeMap = {
        1: '一年级',
        2: '二年级',
        3: '三年级',
        4: '四年级',
        5: '五年级',
        6: '六年级',
        7: '初一',
        8: '初二',
        9: '初三',
        10: '高一',
        11: '高二',
        12: '高三',

    }
    return gradeMap[level] || level
}





// 过滤后的学生列表
const filteredStudents = computed(() => {
    return studentList.value
})

import { StudentList } from '@/api/student'
// 获取学生列表
const getStudentList = async () => {
    loading.value = true
    try {
        const params = {
            userName: searchQuery.value,
            role: 1,
            pageIndex: currentPage.value,
            pageSize: pageSize.value
        }
        const res = await StudentList(params);
        console.log("数据：", res);
        studentList.value = res.response.list || []
        console.log("学生列表数据：", studentList.value);

        totalStudents.value = res.response.total || 0

    } catch (error) {
        ElMessage.error('获取学生列表失败')
        console.error('获取学生列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    getStudentList()
}

// 清空搜索
const handleSearchClear = () => {
    searchQuery.value = ''
    handleSearch()
}

// 新增学生
const handleAdd = () => {
    router.push("/StudentAdd")
}

// 编辑学生
const handleEdit = async (row) => {
    localStorage.setItem('editStudent', JSON.stringify(row))
    // 标记是编辑模式
    localStorage.setItem('isEdit', '1')
    router.push("/StudentAdd")
}

import { ChangeStatus } from "@/api/student"
// 切换状态（禁用/启用）
const handleToggleStatus = async (row) => {
    const res = await ChangeStatus(row.id)
    if(res.code == 1){
        ElMessage.info('状态切换成功')
        getStudentList()
    }else{
        ElMessage.error('状态切换失败')
    }
}

import { del } from '@/api/student'

// 删除学生
const handleDelete = (row) => {
    ElMessageBox.confirm(
        `确定要删除学生 ${row.realName} 吗？`,
        '确认删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const res = await del(row.id)
            console.log(res);

            if (res.code === 1) {
                ElMessage.success('删除成功')
                getStudentList()
            } else {
                ElMessage.error('删除失败')
            }
        })
        .catch(() => {
            ElMessage.info('已取消删除')
        })
}




// 分页大小变化
const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    getStudentList()
}

// 当前页变化
const handleCurrentChange = (val) => {
    currentPage.value = val
    getStudentList()
}

// 组件挂载时获取数据
onMounted(() => {
    getStudentList()
})
</script>

<style scoped>
.box-card {
    box-shadow: none !important;
    border: none !important;
}

.username-label {
    font-family: 'Microsoft YaHei', sans-serif;
    font-size: 16px;
    color: #333;
    font-weight: 600;
    letter-spacing: 1px;
}

.student-container {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-bar {
    margin-bottom: 20px;
}

.top_btn {
    margin-left: 10px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>